package com.imooc.course.server.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.imooc.course.server.dao.TeacherDao;
import com.imooc.course.server.dto.PageDto;
import com.imooc.course.server.dto.TeacherDto;
import com.imooc.course.server.entity.Teacher;
import com.imooc.course.server.entity.TeacherExample;
import com.imooc.course.server.service.TeacherService;
import com.imooc.course.server.utils.CopyUtil;
import com.imooc.course.server.utils.UuidUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service("teacherService")
public class TeacherServiceImpl implements TeacherService {

    private static final Logger log = LoggerFactory.getLogger(TeacherServiceImpl.class);

    @Resource(name = "teacherDao")
    private TeacherDao teacherDao;

    /**
     * 列表查询
     * @param pageDto
     */
    @Override
    public void getList(PageDto pageDto) {
        PageHelper.startPage(pageDto.getPage(),pageDto.getSize());

        TeacherExample teacherExample = new TeacherExample();
        List<Teacher> teacherList = teacherDao.selectByExample(teacherExample);

        PageInfo<Teacher> teacherPageInfo = new PageInfo<>(teacherList);
        pageDto.setTotal(teacherPageInfo.getTotal());

        List<TeacherDto> teacherDtoList = CopyUtil.copyList(teacherList, TeacherDto.class);

        pageDto.setList(teacherDtoList);
    }

    @Override
    public List<TeacherDto> getAll() {
        TeacherExample example = new TeacherExample();
        List<Teacher> teacherList = teacherDao.selectByExample(example);
        return CopyUtil.copyList(teacherList, TeacherDto.class);
    }

    /**
     * 保存，id有值为更新，id无值为新增
     * @param teacherDto
     */
    @Override
    public void save(TeacherDto teacherDto) {
        Teacher copy = CopyUtil.copy(teacherDto, Teacher.class);
        String id = teacherDto.getId() != null ? teacherDto.getId().trim() : teacherDto.getId();
        if (StringUtils.isEmpty(id)) {
            this.addTeacher(copy);
        }else{
            this.updateTeacher(copy);
        }
    }

    private void updateTeacher(Teacher copy) {
        teacherDao.updateByPrimaryKeySelective(copy);
    }

    private void addTeacher(Teacher copy) {
        copy.setId(UuidUtil.getShortUuid());
        teacherDao.insertSelective(copy);
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void delete(String id) {
        teacherDao.deleteByPrimaryKey(id);
    }

    @Override
    public TeacherDto getById(String teacherId) {
        Teacher teacher = teacherDao.selectByPrimaryKey(teacherId);
        return CopyUtil.copy(teacher,TeacherDto.class);
    }
}
